package com.bnq.control.desktop.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;


import com.bnq.control.common.utils.CloseUtils;
import com.bnq.control.desktop.entity.SDCardEntity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DesktopPluginUtils {

    /**
     * 錄像剩餘空間
     */
    private static final int AVAILESIZE_RECORDER = 20;

    public static boolean canSaveOutSDCard(String path) {
        try {
            File file = new File(path, "/oray/temp/");
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                return mkdirs;
            } else {
                boolean delete = file.delete();
                return delete;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 是否有剩余自定义的空间大小
     *
     * @param sdPath
     * @return
     */
    public static boolean isAvailable(String sdPath) {
        return getAvaileSize(sdPath) > AVAILESIZE_RECORDER;
    }

    public static long getAvaileSize(String path) {

        StatFs stat = new StatFs(path);

        long blockSize = stat.getBlockSize();   // 获得一个扇区的大小

        long totalBlocks = stat.getBlockCount();    // 获得扇区的总数

        long availableBlocks = stat.getAvailableBlocks();   // 获得可用的扇区数量

        long availMemory = (availableBlocks * blockSize) / 1024 / 1024; //MB

        return availMemory;

    }

    /**
     * 返回sd路径，如果有外置sd卡，则先返回外置路径，否则返回内置sd卡路径
     *
     * @return
     */
    public static SDCardEntity getSdCardPath() {
        SDCardEntity sdEntity = new SDCardEntity();
        String sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
        List<String> extSDCardPaths = getExtSDCardPaths();
        if (null != extSDCardPaths && extSDCardPaths.size() > 0) {
            for (String path : extSDCardPaths) {
                if (path.toUpperCase().contains("sd".toUpperCase())) {
                    sd_default = path;
                    break;
                }
            }
        } else {
            String extSDCardPath = getExtSDCardPath();
            if (Build.VERSION.SDK_INT >= 23 && !TextUtils.isEmpty(extSDCardPath)) {
                sd_default = extSDCardPath;
            }
        }
        if (!sd_default.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
            String sd_cache = sd_default;

	    	/*小米4.2的手机内部存储是sdcard1,插入sd卡，Environment.getExternalStorageDirectory()会变成外置sd卡的路径sdcard0,
  	  		所以针对小米系统4.2特别处理
	    	 */
            if (Build.VERSION.SDK_INT < 18 && Build.BRAND.toUpperCase().equals("Xiaomi".toUpperCase())) {
                sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
            }
            sdEntity.isOutSD = true;
            if (!isAvailable(sd_default)) {//如果外置sd没有空间，就返回内置sd卡
                if (Build.VERSION.SDK_INT < 18 && Build.BRAND.toUpperCase().equals("Xiaomi".toUpperCase())) {
                    sd_default = sd_cache;
                } else {
                    sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
                }
                sdEntity.isOutSD = false;
            }
        } else {
            sdEntity.isOutSD = false;
        }
        sdEntity.sdPath = sd_default;
        if (sdEntity.isOutSD && !canSaveOutSDCard(sd_default)) {//如果有外置sd卡但是不能存儲，則返回內置sd卡
            sdEntity.sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            sdEntity.isOutSD = false;
        }
        return sdEntity;
    }

    public static String getExtSDCardPath() {

        String exPath = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("ls /storage");
            is = process.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            String s = "";
            while ((line = br.readLine()) != null) {
                s = line + ",";
                if (!TextUtils.isEmpty(line) && !line.toUpperCase().contains("emulated".toUpperCase())
                        && !line.toUpperCase().contains("self".toUpperCase())) {
                    exPath = "/storage/" + line;
                }
            }
            Log.i("storage", s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeQuietly(is, isr, br);
        }
        return exPath;
    }


    /**
     * 获取外置sd卡集合
     *
     * @return
     */
    public static List<String> getExtSDCardPaths() {
        List<String> paths = new ArrayList<String>();
        String extFileStatus = Environment.getExternalStorageState();
        File extFile = Environment.getExternalStorageDirectory();
        if (extFileStatus.endsWith(Environment.MEDIA_UNMOUNTED)
                && extFile.exists() && extFile.isDirectory()
                && extFile.canWrite()) {
            paths.add(extFile.getAbsolutePath());
        }
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            // obtain executed result of command line code of 'mount', to judge
            // whether tfCard exists by the result
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("mount");
            is = process.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            int mountPathIndex = 1;
            while ((line = br.readLine()) != null) {
                // format of sdcard file system: vfat/fuse
                if ((!line.contains("fat") && !line.contains("fuse") && !line
                        .contains("storage"))
                        || line.contains("secure")
                        || line.contains("asec")
                        || line.contains("firmware")
                        || line.contains("shell")
                        || line.contains("obb")
                        || line.contains("legacy") || line.contains("data")) {
                    continue;
                }
                String[] parts = line.split(" ");
                int length = parts.length;
                if (mountPathIndex >= length) {
                    continue;
                }
                String mountPath = parts[mountPathIndex];
                if (!mountPath.contains("/") || mountPath.contains("data") || mountPath.contains("Data")) {
                    continue;
                }
                File mountRoot = new File(mountPath);
                if (!mountRoot.exists() || !mountRoot.isDirectory()
                        || !mountRoot.canWrite()) {
                    continue;
                }
                boolean equalsToPrimarySD = mountPath.equals(extFile
                        .getAbsolutePath());
                if (equalsToPrimarySD) {
                    continue;
                }
                paths.add(mountPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeQuietly(is);
            CloseUtils.closeQuietly(isr);
            CloseUtils.closeQuietly(br);
        }
        return paths;
    }


    /**
     * 截屏方法
     *
     * @param rootView 根view
     * @param tag      类的tag名称，日志输出
     */
    public static void screenShot(View rootView, String tag, Context context) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.US);
        String sdPath = getSdCardPath().sdPath;
        String path = sdPath + "/oray/picture/";
        String filename = sdf.format(new Date()) + ".png";
        File file = new File(path, filename);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache();
        Bitmap bitmap = rootView.getDrawingCache();
        if (null != bitmap) {
            Log.i(tag, "bitmap got!");
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                Log.i(tag, "file " + filename + "output done.");
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                CloseUtils.closeQuietly(fos);
            }
        } else {
            Log.e(tag, "bitmap is NULL!");
        }

        //把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, filename, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        rootView.destroyDrawingCache();
    }

    /**
     * 通知媒体库更新文件
     *
     * @param context
     * @param filePath 文件全路径
     */
    public static void scanFile(Context context, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        context.sendBroadcast(scanIntent);
    }

    /**
     * 旋转图片
     *
     * @param bm
     * @param orientationDegree
     * @return
     */
    public static Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);
        return bm1;
    }

}
